const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');

const session  = require("express-session");


const config = require('./config')
const jwt  = require("express-jwt");

// 路由
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const articleRouter = require('./routes/article');

const app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

app.use(logger('dev'));
app.use(express.json());

app.use(jwt({secret: config.jwtSecretKey}).unless({path:[/^\api/,'/api/login','/api/register']}))
// 配置解析表单数据的中间件 这个中间件只能解析application/x-www-form-urlencode 格式的表单数据
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// session中间件
app.use(session({
  secret:'boke',
  resave:false,
  saveUninitialized:true
}))

// 封装send
app.use((req,res,next)=>{

  res.error = function(err,code = 1){
      res.send({
          code,
          // 判断是错误本身还是错误对象
          message: err instanceof Error ? err.message : err
      })
      
  }
      next()
})
app.use('/', indexRouter);
app.use('/api', usersRouter);
app.use('/api',articleRouter)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  console.log('aa',err);
  // if(err.name === 'UnauthorizedError') return res.send('身份认证失败')
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
